//
//  MineOrderViewController.swift
//  Box
//
//  Created by mn on 2025/3/30.
//

import UIKit

class MineOrderViewController: BaseViewController{
    //订单状态 0待支付 1待发货 2待收货 3已完成 4已取消 不传代表查询所有状态
    var selectIndex: Int = 0{
        didSet{
            typeView.selectIndex = selectIndex
        }
    }
    let typeView = OrderTypeView()
    private let tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        nav.title = "我的订单"
        view.addSubview(typeView)
        typeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(nav.snp.bottom)
            make.height.equalTo(50)
        }
        typeView.tapIndex = {
            [weak self]  in
            guard let self else { return }
            page = 1
            tableView.headerBeginRefreshing()
        }
        view.backgroundColor = .white
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.tableFooterView = UIView()

        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(typeView.snp.bottom).offset(5)
            make.bottom.equalToSuperview()
        }
        tableView.registerCell(OrderListCell.self)
        tableView.addMJHeader {
            [weak self] in
            self?.page = 1
            self?.getMyStoreList()
        }
        tableView.addMJFooter {
            [weak self] in
            guard let self else { return }
            page += 1
            getMyStoreList()
        }
        tableView.headerBeginRefreshing()
    }
    var orderModels = [OrderModel]()
    var page = 1
    func getMyStoreList() {
        APIService.request(api: .orderList(page: page, status: typeView.currentIndex)) {
            [weak self] (result, response) in
            self?.tableView.endAllRefreshing()
            if result.success, let models: OrderListData = Decoder.data(response) {
                if self?.page == 1 {
                    self?.orderModels.removeAll()
                }
                self?.orderModels.append(contentsOf: models.data)
                self?.tableView.reloadData()
            }
        }
    }
}
extension MineOrderViewController: UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        orderModels.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: OrderListCell = tableView.cell(indexPath)
        cell.configure(with: orderModels[indexPath.row])
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = OrderDetailViewController(orderModel: orderModels[indexPath.row])
        navigationController?.push(vc)
    }
}
